import os
import requests
import json
import ctypes
import sys
import random
import time
import schedule
import threading
from datetime import datetime, timedelta
from urllib.parse import urljoin
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                             QHBoxLayout, QPushButton, QLabel, QSpinBox, 
                             QGroupBox, QTextEdit, QProgressBar, QMessageBox,
                             QListWidget, QListWidgetItem, QSplitter, 
                             QGridLayout, QCalendarWidget, QSizePolicy,
                             QTimeEdit, QSystemTrayIcon, QMenu, QAction)
from PyQt5.QtCore import Qt, QTimer, pyqtSignal, QDate, QThread, pyqtSlot, QTime, QPropertyAnimation, QEasingCurve, QPoint, QSize
from PyQt5.QtGui import QFont, QPalette, QColor, QTextCharFormat, QBrush, QIcon, QPixmap, QPainter, QPen

class WallpaperWorker(QThread):
    """壁纸工作线程，用于异步设置壁纸"""
    finished_signal = pyqtSignal(bool, str)  # 成功状态, 消息
    
    def __init__(self, image_path, date_str, title):
        super().__init__()
        self.image_path = image_path
        self.date_str = date_str
        self.title = title
        
    def run(self):
        """在子线程中执行壁纸设置"""
        try:
            if sys.platform == "win32":
                # 在子线程中设置壁纸
                result = ctypes.windll.user32.SystemParametersInfoW(20, 0, self.image_path, 3)
                if result:
                    self.finished_signal.emit(True, f"已设置壁纸: {self.date_str} - {self.title}")
                else:
                    self.finished_signal.emit(False, f"设置壁纸失败: Windows API调用失败")
            else:
                # 其他平台的设置代码...
                self.finished_signal.emit(False, f"不支持的操作系统: {sys.platform}")
        except Exception as e:
            self.finished_signal.emit(False, f"设置壁纸异常: {str(e)}")

class BingWallpaperApp(QMainWindow):
    update_signal = pyqtSignal(str)
    
    def __init__(self):
        super().__init__()
        self.wallpapers_dir = os.path.join("E:\\", "pic", "BingWallpapers")
        self.wallpaper_info_file = os.path.join(self.wallpapers_dir, "wallpaper_info.txt")
        self.wallpaper_info = {}
        self.current_index = 0
        self.wallpapers_list = []
        self.is_auto_switch = False
        self.switch_timer = QTimer()
        self.countdown_timer = QTimer()
        self.remaining_seconds = 0
        self.wallpaper_dates = set()
        self.wallpaper_worker = None
        self.is_setting_wallpaper = False
        self.is_first_load = True
        self.is_quitting = False
        self.tray_icon = None
        
        # 隐藏标题栏并设置无边框窗口
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        
        self.init_ui()
        self.create_tray_icon()
        self.load_wallpaper_info()
        self.load_wallpapers()
        self.connect_signals()
        
        # 启动时检查今日壁纸
        QTimer.singleShot(1000, self.check_and_download_today_wallpaper)
        
    def create_icon(self):
        """使用本地图标"""
        # 指定本地 .ico 文件路径
        # icon_path = "icon.ico"  # 替换为你的 .ico 文件路径
        # if not os.path.exists(icon_path):
        #     print(f"错误：文件不存在 -> {icon_path}")
        # icon = QIcon(icon_path)
        # print(icon)
        
        # # 可选：设置图标大小（如果需要）
        # # icon = QIcon(icon.pixmap(QSize(64, 64)))  # 调整为 32x32 像素
        # return icon
    
        """创建应用程序图标"""
        # 创建一个64x64的图标
        pixmap = QPixmap(64, 64)
        pixmap.fill(Qt.transparent)
        
        # 绘制图标
        painter = QPainter(pixmap)
        
        # 背景圆形
        painter.setBrush(QBrush(QColor(52, 152, 219)))  # 蓝色
        painter.setPen(QPen(QColor(41, 128, 185), 3))
        painter.drawEllipse(4, 4, 56, 56)
        
        # 内圆（代表壁纸）
        painter.setBrush(QBrush(QColor(231, 76, 60)))   # 红色
        painter.setPen(QPen(QColor(192, 57, 43), 2))
        painter.drawEllipse(16, 16, 32, 32)
        
        # 山脉形状
        painter.setBrush(QBrush(QColor(46, 204, 113)))  # 绿色
        points = [
            (20, 40), (32, 24), (44, 40), (36, 48), (28, 48)
        ]
        painter.drawPolygon(*[QPoint(x, y) for x, y in points])
        
        # 太阳
        painter.setBrush(QBrush(QColor(241, 196, 15)))  # 黄色
        painter.drawEllipse(46, 18, 8, 8)
        
        painter.end()
        
        return QIcon(pixmap)
        
    def create_tray_icon(self):
        """创建系统托盘图标"""
        # 检查系统是否支持托盘图标
        if not QSystemTrayIcon.isSystemTrayAvailable():
            QMessageBox.critical(None, "系统托盘", "系统不支持托盘图标")
            return
            
        # 创建托盘图标
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(self.create_icon())
        self.tray_icon.setToolTip("Bing壁纸管理器\n双击显示/隐藏窗口\n右键查看更多选项")
        
        # 创建托盘菜单
        tray_menu = QMenu(self)
        
        # 显示/隐藏窗口
        show_action = QAction("🪟 显示/隐藏窗口", self)
        show_action.triggered.connect(self.toggle_window)
        tray_menu.addAction(show_action)
        
        tray_menu.addSeparator()
        
        # 壁纸控制菜单
        wallpaper_menu = tray_menu.addMenu("🎨 壁纸控制")
        
        prev_action = QAction("◀ 上一张壁纸", self)
        prev_action.triggered.connect(self.previous_wallpaper)
        wallpaper_menu.addAction(prev_action)
        
        next_action = QAction("下一张壁纸 ▶", self)
        next_action.triggered.connect(self.next_wallpaper)
        wallpaper_menu.addAction(next_action)
        
        random_action = QAction("🎲 随机壁纸", self)
        random_action.triggered.connect(self.random_wallpaper)
        wallpaper_menu.addAction(random_action)
        
        tray_menu.addSeparator()
        
        # 下载菜单
        download_menu = tray_menu.addMenu("⬇️ 下载壁纸")
        
        today_action = QAction("📅 今日壁纸", self)
        today_action.triggered.connect(self.download_daily_wallpaper)
        download_menu.addAction(today_action)
        
        history_action = QAction("📚 历史7天壁纸", self)
        history_action.triggered.connect(self.download_historical_wallpapers)
        download_menu.addAction(history_action)
        
        tray_menu.addSeparator()
        
        # 自动切换菜单
        auto_menu = tray_menu.addMenu("⏰ 自动切换")
        
        start_auto_action = QAction("▶ 开始自动切换", self)
        start_auto_action.triggered.connect(self.start_auto_switch)
        auto_menu.addAction(start_auto_action)
        
        stop_auto_action = QAction("⏹ 停止自动切换", self)
        stop_auto_action.triggered.connect(self.stop_auto_switch)
        auto_menu.addAction(stop_auto_action)
        
        tray_menu.addSeparator()
        
        # 退出程序
        quit_action = QAction("❌ 退出程序", self)
        quit_action.triggered.connect(self.quit_application)
        tray_menu.addAction(quit_action)
        
        # 设置托盘菜单
        self.tray_icon.setContextMenu(tray_menu)
        
        # 托盘图标点击事件
        self.tray_icon.activated.connect(self.on_tray_icon_activated)
        
        # 显示托盘图标
        self.tray_icon.show()
        
        # 显示欢迎消息
        self.tray_icon.showMessage(
            "Bing壁纸管理器",
            "程序已启动并在系统托盘中运行\n双击图标显示/隐藏窗口\n右键点击查看更多选项",
            QSystemTrayIcon.Information,
            5000
        )
        
    def on_tray_icon_activated(self, reason):
        """托盘图标激活事件"""
        if reason == QSystemTrayIcon.DoubleClick:
            self.toggle_window()
        elif reason == QSystemTrayIcon.Trigger:
            self.toggle_window()
            
    def toggle_window(self):
        """切换窗口显示状态"""
        if self.isVisible():
            self.hide()
        else:
            self.show()
            self.raise_()
            self.activateWindow()
            
    def closeEvent(self, event):
        """重写关闭事件，最小化到托盘"""
        if not self.is_quitting:
            event.ignore()
            self.hide()
            if self.tray_icon:
                self.tray_icon.showMessage(
                    "Bing壁纸管理器",
                    "程序已最小化到系统托盘\n双击托盘图标重新显示窗口",
                    QSystemTrayIcon.Information,
                    2000
                )
        else:
            event.accept()
            
    def quit_application(self):
        """退出应用程序"""
        self.is_quitting = True
        
        # 确认退出
        reply = QMessageBox.question(
            self,
            "确认退出",
            "确定要退出Bing壁纸管理器吗？\n退出后自动切换功能将停止",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 停止所有定时器
            self.switch_timer.stop()
            self.countdown_timer.stop()
                
            # 隐藏托盘图标
            if self.tray_icon:
                self.tray_icon.hide()
                
            # 退出应用
            QApplication.quit()
            
    def show_tray_notification(self, message, title="Bing壁纸管理器"):
        """显示托盘通知"""
        if self.tray_icon:
            self.tray_icon.showMessage(
                title,
                message,
                QSystemTrayIcon.Information,
                2000
            )
        
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口图标
        self.setWindowIcon(self.create_icon())
        
        self.setGeometry(100, 100, 900, 700)
        
        # 设置更精美的样式
        self.setStyleSheet("""
            /* 主窗口样式 */
            QMainWindow {
                background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1,
                                          stop: 0 #1e3c72, stop: 0.5 #2a5298, stop: 1 #1e3c72);
                color: #ffffff;
                border: 2px solid #4a90e2;
                border-radius: 12px;
            }
            
            /* 自定义标题栏 */
            #title_bar {
                background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,
                                          stop: 0 #2c3e50, stop: 1 #34495e);
                border-top-left-radius: 10px;
                border-top-right-radius: 10px;
                border-bottom: 1px solid #3498db;
                padding: 8px;
            }
            
            #title_label {
                color: #ecf0f1;
                font-size: 14px;
                font-weight: bold;
                background: transparent;
                border: none;
            }
            
            #close_button {
                background: #e74c3c;
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                padding: 4px 8px;
                min-width: 20px;
                min-height: 20px;
            }
            
            #close_button:hover {
                background: #c0392b;
            }
            
            #minimize_button {
                background: #f39c12;
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                padding: 4px 8px;
                min-width: 20px;
                min-height: 20px;
            }
            
            #minimize_button:hover {
                background: #e67e22;
            }
            
            /* 组框样式 */
            QGroupBox {
                color: #ecf0f1;
                font-weight: bold;
                font-size: 13px;
                border: 2px solid #3498db;
                border-radius: 8px;
                margin-top: 1ex;
                padding-top: 12px;
                background: rgba(52, 73, 94, 0.8);
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 12px;
                padding: 0 8px 0 8px;
                color: #3498db;
                background: rgba(44, 62, 80, 0.9);
                border-radius: 4px;
            }
            
            /* 按钮样式 */
            QPushButton {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #3498db, stop: 1 #2980b9);
                border: 1px solid #2573a7;
                border-radius: 6px;
                color: white;
                padding: 8px 16px;
                font-weight: bold;
                font-size: 13px;
            }
            QPushButton:hover {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #3cb0fd, stop: 1 #3498db);
            }
            QPushButton:pressed {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #2980b9, stop: 1 #2471a3);
            }
            QPushButton#control {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #9b59b6, stop: 1 #8e44ad);
                border: 1px solid #7d3c98;
            }
            QPushButton#control:hover {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #a569bd, stop: 1 #9b59b6);
            }
            QPushButton#control:pressed {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #8e44ad, stop: 1 #7d3c98);
            }
            QPushButton:disabled {
                background: #95a5a6;
                border: 1px solid #7f8c8d;
                color: #bdc3c7;
            }
            
            /* 时间编辑框 */
            QTimeEdit {
                background: rgba(52, 73, 94, 0.9);
                border: 1px solid #3498db;
                border-radius: 4px;
                color: white;
                padding: 5px;
                selection-background-color: #3498db;
            }
            
            /* 进度条 */
            QProgressBar {
                border: 1px solid #34495e;
                border-radius: 5px;
                text-align: center;
                color: white;
                background: rgba(52, 73, 94, 0.8);
            }
            QProgressBar::chunk {
                background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,
                                          stop: 0 #2ecc71, stop: 1 #27ae60);
                border-radius: 4px;
            }
            
            /* 标签样式 */
            QLabel {
                color: #ecf0f1;
                background: rgba(52, 73, 94, 0.7);
                padding: 8px;
                border-radius: 6px;
                border: 1px solid #3498db;
            }
            QLabel#status {
                color: #3498db;
                background: transparent;
                padding: 4px;
                border: none;
                font-weight: bold;
                font-size: 12px;
            }
            QLabel#current {
                color: #f1c40f;
                background: rgba(52, 73, 94, 0.9);
                padding: 10px;
                border: 2px solid #f39c12;
                border-radius: 8px;
                font-weight: bold;
                font-size: 13px;
            }
            QLabel#countdown {
                color: #e74c3c;
                background: rgba(52, 73, 94, 0.9);
                padding: 8px;
                border: 2px solid #e74c3c;
                border-radius: 8px;
                font-weight: bold;
                font-size: 13px;
                text-align: center;
            }
            
            /* 日历样式 */
            QCalendarWidget {
                background: rgba(52, 73, 94, 0.9);
                color: white;
                border: 2px solid #3498db;
                border-radius: 8px;
            }
            QCalendarWidget QWidget {
                alternate-background-color: #2c3e50;
            }
            QCalendarWidget QToolButton {
                color: white;
                background: #3498db;
                border: 1px solid #2980b9;
                border-radius: 4px;
                padding: 5px;
                font-weight: bold;
            }
            QCalendarWidget QToolButton:hover {
                background: #3cb0fd;
            }
            QCalendarWidget QMenu {
                background: #34495e;
                color: white;
                border: 1px solid #3498db;
            }
            QCalendarWidget QSpinBox {
                background: #34495e;
                color: white;
                border: 1px solid #3498db;
                border-radius: 4px;
                padding: 2px;
            }
            QCalendarWidget QAbstractItemView:enabled {
                color: white;
                background: #2c3e50;
                selection-background-color: #3498db;
                selection-color: white;
                border: 1px solid #34495e;
            }
            QCalendarWidget QAbstractItemView:disabled {
                color: #7f8c8d;
                background: #34495e;
            }
        """)
        
        # 中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        layout.setContentsMargins(8, 8, 8, 8)
        layout.setSpacing(8)
        
        # 添加自定义标题栏
        self.create_title_bar(layout)
        
        # 创建主内容区域
        self.main_content = QWidget()
        main_layout = QVBoxLayout(self.main_content)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        splitter.setHandleWidth(2)
        splitter.setStyleSheet("""
            QSplitter::handle {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                                          stop:0 #3498db, stop:1 #9b59b6);
                border: 1px solid #2980b9;
                border-radius: 1px;
            }
            QSplitter::handle:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                                          stop:0 #3cb0fd, stop:1 #a569bd);
            }
        """)
        
        # 左侧控制面板
        self.left_panel = self.create_control_panel()
        splitter.addWidget(self.left_panel)
        
        # 右侧日历面板
        self.right_panel = self.create_calendar_panel()
        splitter.addWidget(self.right_panel)
        
        # 设置分割器比例
        splitter.setStretchFactor(0, 1)
        splitter.setStretchFactor(1, 2)
        
        main_layout.addWidget(splitter)
        layout.addWidget(self.main_content)
        
        # 状态栏
        self.status_label = QLabel("就绪")
        self.status_label.setObjectName("status")
        self.statusBar().addWidget(self.status_label)
        
    def create_title_bar(self, parent_layout):
        """创建自定义标题栏"""
        title_bar = QWidget()
        title_bar.setObjectName("title_bar")
        title_bar.setFixedHeight(35)
        
        title_layout = QHBoxLayout(title_bar)
        title_layout.setContentsMargins(10, 0, 10, 0)
        
        # 标题标签
        title_label = QLabel("🎨 Bing壁纸管理器")
        title_label.setObjectName("title_label")
        
        # 拖拽区域
        title_layout.addWidget(title_label)
        title_layout.addStretch()
        
        # 置顶按钮
        self.pin_btn = QPushButton("📌")
        self.pin_btn.setObjectName("minimize_button")
        self.pin_btn.setFixedSize(20, 20)
        self.pin_btn.setToolTip("切换置顶状态")
        self.pin_btn.clicked.connect(self.toggle_always_on_top)
        
        # 最小化按钮
        minimize_btn = QPushButton("−")
        minimize_btn.setObjectName("minimize_button")
        minimize_btn.setFixedSize(20, 20)
        minimize_btn.clicked.connect(self.hide_window)
        
        # 关闭按钮
        close_btn = QPushButton("×")
        close_btn.setObjectName("close_button")
        close_btn.setFixedSize(20, 20)
        close_btn.clicked.connect(self.hide_window)
        
        title_layout.addWidget(self.pin_btn)
        title_layout.addWidget(minimize_btn)
        title_layout.addWidget(close_btn)
        
        parent_layout.addWidget(title_bar)
        
    def toggle_always_on_top(self):
        """切换置顶状态"""
        if self.windowFlags() & Qt.WindowStaysOnTopHint:
            self.setWindowFlags(Qt.FramelessWindowHint)
            self.pin_btn.setText("📌")
            self.pin_btn.setToolTip("置顶窗口")
        else:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
            self.pin_btn.setText("📍")
            self.pin_btn.setToolTip("取消置顶")
        self.show()
        
    def hide_window(self):
        """隐藏窗口"""
        self.hide()
        
    def create_control_panel(self):
        """创建左侧控制面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        layout.setSpacing(10)
        layout.setContentsMargins(8, 8, 8, 8)
        
        # 壁纸控制组
        control_group = QGroupBox("🎮 壁纸控制")
        control_layout = QVBoxLayout()
        control_layout.setSpacing(8)
        
        # 导航按钮
        nav_layout = QHBoxLayout()
        self.prev_btn = QPushButton("◀ 上一张")
        self.next_btn = QPushButton("下一张 ▶")
        self.random_btn = QPushButton("🎲 随机一张")
        
        self.prev_btn.setObjectName("control")
        self.next_btn.setObjectName("control")
        self.random_btn.setObjectName("control")
        
        nav_layout.addWidget(self.prev_btn)
        nav_layout.addWidget(self.next_btn)
        nav_layout.addWidget(self.random_btn)
        control_layout.addLayout(nav_layout)
        
        # 当前壁纸信息
        self.current_wallpaper_label = QLabel("当前壁纸: 无")
        self.current_wallpaper_label.setWordWrap(True)
        self.current_wallpaper_label.setObjectName("current")
        control_layout.addWidget(self.current_wallpaper_label)
        
        control_group.setLayout(control_layout)
        layout.addWidget(control_group)
        
        # 自动切换组
        auto_group = QGroupBox("⏰ 自动切换设置")
        auto_layout = QVBoxLayout()
        auto_layout.setSpacing(8)
        
        # 间隔时间设置
        interval_layout = QHBoxLayout()
        interval_layout.addWidget(QLabel("🕐 切换间隔:"))
        
        self.time_edit = QTimeEdit()
        self.time_edit.setDisplayFormat("HH:mm:ss")
        self.time_edit.setTime(QTime(0, 1, 0))
        self.time_edit.setTimeRange(QTime(0, 0, 1), QTime(23, 59, 59))
        
        interval_layout.addWidget(self.time_edit)
        interval_layout.addStretch()
        
        auto_layout.addLayout(interval_layout)
        
        # 总间隔时间显示
        self.total_interval_label = QLabel("总间隔: 1分钟 0秒")
        self.total_interval_label.setAlignment(Qt.AlignCenter)
        self.total_interval_label.setStyleSheet("color: #3498db; font-weight: bold; background: rgba(52, 73, 94, 0.7); padding: 6px; border-radius: 4px;")
        auto_layout.addWidget(self.total_interval_label)
        
        # 倒计时显示
        self.countdown_label = QLabel("自动切换已停止")
        self.countdown_label.setObjectName("countdown")
        self.countdown_label.setAlignment(Qt.AlignCenter)
        auto_layout.addWidget(self.countdown_label)
        
        # 自动切换控制
        switch_layout = QHBoxLayout()
        self.auto_switch_btn = QPushButton("▶ 开始自动切换")
        self.stop_auto_btn = QPushButton("⏹ 停止自动切换")
        self.auto_switch_btn.setObjectName("control")
        self.stop_auto_btn.setObjectName("control")
        self.stop_auto_btn.setEnabled(False)
        
        switch_layout.addWidget(self.auto_switch_btn)
        switch_layout.addWidget(self.stop_auto_btn)
        auto_layout.addLayout(switch_layout)
        
        auto_group.setLayout(auto_layout)
        layout.addWidget(auto_group)
        
        # 壁纸管理组
        manage_group = QGroupBox("📁 壁纸管理")
        manage_layout = QVBoxLayout()
        manage_layout.setSpacing(8)
        
        self.download_btn = QPushButton("⬇️ 下载今日壁纸")
        self.download_history_btn = QPushButton("📅 下载历史7天壁纸")
        self.refresh_btn = QPushButton("🔄 刷新日历")
        
        manage_layout.addWidget(self.download_btn)
        manage_layout.addWidget(self.download_history_btn)
        manage_layout.addWidget(self.refresh_btn)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        manage_layout.addWidget(self.progress_bar)
        
        manage_group.setLayout(manage_layout)
        layout.addWidget(manage_group)
        
        layout.addStretch()
        return panel

    def create_calendar_panel(self):
        """创建右侧日历面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        layout.setSpacing(10)
        layout.setContentsMargins(8, 8, 8, 8)
        
        calendar_group = QGroupBox("📅 壁纸日历")
        calendar_layout = QVBoxLayout()
        calendar_layout.setSpacing(8)
        
        # 创建日历控件
        self.calendar = QCalendarWidget()
        self.calendar.setGridVisible(True)
        self.calendar.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader)
        
        # 设置日期范围
        today = QDate.currentDate()
        max_date = today
        min_date = QDate(2020, 1, 1)
        self.calendar.setDateRange(min_date, max_date)
        self.calendar.setSelectedDate(today)
        
        self.calendar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        calendar_layout.addWidget(self.calendar)
        
        # 日历操作按钮
        calendar_buttons_layout = QHBoxLayout()
        self.today_btn = QPushButton("🏠 跳转到今天")
        self.selected_date_btn = QPushButton("⬇️ 下载选中日期壁纸")
        
        self.today_btn.setObjectName("control")
        self.selected_date_btn.setObjectName("control")
        
        calendar_buttons_layout.addWidget(self.today_btn)
        calendar_buttons_layout.addWidget(self.selected_date_btn)
        calendar_buttons_layout.addStretch()
        
        calendar_layout.addLayout(calendar_buttons_layout)
        
        calendar_group.setLayout(calendar_layout)
        layout.addWidget(calendar_group)
        
        return panel

    # 鼠标事件处理，实现窗口拖拽
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drag_start_position = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()
            
    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton and hasattr(self, 'drag_start_position'):
            self.move(event.globalPos() - self.drag_start_position)
            event.accept()

    def connect_signals(self):
        """连接信号和槽"""
        # 按钮点击事件
        self.prev_btn.clicked.connect(self.previous_wallpaper)
        self.next_btn.clicked.connect(self.next_wallpaper)
        self.random_btn.clicked.connect(self.random_wallpaper)
        self.auto_switch_btn.clicked.connect(self.start_auto_switch)
        self.stop_auto_btn.clicked.connect(self.stop_auto_switch)
        self.download_btn.clicked.connect(self.download_daily_wallpaper)
        self.download_history_btn.clicked.connect(self.download_historical_wallpapers)
        self.refresh_btn.clicked.connect(self.load_wallpapers)
        
        # 日历相关信号
        self.calendar.clicked.connect(self.on_calendar_date_clicked)
        self.calendar.selectionChanged.connect(self.on_calendar_selection_changed)
        self.today_btn.clicked.connect(self.jump_to_today)
        self.selected_date_btn.clicked.connect(self.download_selected_date)
        
        # 定时器
        self.switch_timer.timeout.connect(self.auto_switch_wallpaper)
        self.countdown_timer.timeout.connect(self.update_countdown)
        
        # 时间控件改变时重新启动定时器
        self.time_edit.timeChanged.connect(self.on_time_changed)

    def get_total_seconds(self):
        """从时间控件获取总秒数"""
        time = self.time_edit.time()
        return time.hour() * 3600 + time.minute() * 60 + time.second()
        
    def update_total_interval_label(self):
        """更新总间隔时间显示"""
        total_seconds = self.get_total_seconds()
        if total_seconds == 0:
            self.total_interval_label.setText("总间隔: 0秒")
            return
            
        hours = total_seconds // 3600
        minutes = (total_seconds % 3600) // 60
        seconds = total_seconds % 60
        
        parts = []
        if hours > 0:
            parts.append(f"{hours}小时")
        if minutes > 0:
            parts.append(f"{minutes}分钟")
        if seconds > 0 or total_seconds == 0:
            parts.append(f"{seconds}秒")
            
        self.total_interval_label.setText(f"总间隔: {' '.join(parts)}")
        
    def on_time_changed(self):
        """时间改变时更新显示并重新启动定时器"""
        self.update_total_interval_label()
        if self.is_auto_switch:
            self.restart_auto_switch()
            
    def restart_auto_switch(self):
        """重新启动自动切换"""
        if self.is_auto_switch:
            self.switch_timer.stop()
            self.countdown_timer.stop()
            
            total_seconds = self.get_total_seconds()
            if total_seconds < 10:
                self.stop_auto_switch()
                QMessageBox.warning(self, "警告", "间隔时间不能小于10s!")
                return
                
            self.switch_timer.start(total_seconds * 1000)
            self.remaining_seconds = total_seconds
            self.countdown_timer.start(1000)
            self.update_countdown_label()
            
    def update_countdown(self):
        """更新倒计时"""
        if self.remaining_seconds > 0:
            self.remaining_seconds -= 1
            self.update_countdown_label()
        else:
            total_seconds = self.get_total_seconds()
            self.remaining_seconds = total_seconds
            self.update_countdown_label()
            
    def update_countdown_label(self):
        """更新倒计时标签"""
        if self.is_auto_switch:
            total_seconds = self.remaining_seconds
            hours = total_seconds // 3600
            minutes = (total_seconds % 3600) // 60
            seconds = total_seconds % 60
            
            if hours > 0:
                self.countdown_label.setText(f"⏳ 下次切换: {hours:02d}:{minutes:02d}:{seconds:02d}")
            else:
                self.countdown_label.setText(f"⏳ 下次切换: {minutes:02d}:{seconds:02d}")
        else:
            self.countdown_label.setText("⏸ 自动切换已停止")
        
    def check_and_download_today_wallpaper(self):
        """检查并下载今日壁纸（如果不存在）"""
        today_str = QDate.currentDate().toString("yyyy-MM-dd")
        today_wallpaper_path = os.path.join(self.wallpapers_dir, f"bing_{today_str}.jpg")
        
        if not os.path.exists(today_wallpaper_path):
            if self.is_first_load:
                self.status_label.setText("🔍 正在检查今日壁纸...")
                self.is_first_load = False
            self.download_daily_wallpaper()
        else:
            if self.is_first_load:
                # self.status_label.setText("✅ 今日壁纸已存在，正在设置...")
                self.is_first_load = False
                # self.set_wallpaper_async(today_wallpaper_path)

    def set_wallpaper_async(self, image_path):
        """异步设置壁纸"""
        if self.is_setting_wallpaper:
            self.status_label.setText("⏳ 正在设置壁纸，请稍候...")
            return
            
        filename = os.path.basename(image_path)
        date_str = filename[5:15]
        title = self.get_wallpaper_title(date_str)
        
        self.is_setting_wallpaper = True
        self.status_label.setText("🎨 正在设置壁纸...")
        self.set_buttons_enabled(False)
        
        if image_path in self.wallpapers_list:
            self.current_index = self.wallpapers_list.index(image_path)
        
        self.wallpaper_worker = WallpaperWorker(image_path, date_str, title)
        self.wallpaper_worker.finished_signal.connect(self.on_wallpaper_set_finished)
        self.wallpaper_worker.start()
        
    @pyqtSlot(bool, str)
    def on_wallpaper_set_finished(self, success, message):
        """壁纸设置完成回调"""
        self.is_setting_wallpaper = False
        self.set_buttons_enabled(True)
        self.status_label.setText(message)
        
        if success:
            self.update_current_wallpaper_label()
            # 显示托盘通知
            filename = os.path.basename(self.wallpapers_list[self.current_index])
            date_str = filename[5:15]
            title = self.get_wallpaper_title(date_str)
            self.show_tray_notification(f"已设置壁纸: {title}")
        
    def set_buttons_enabled(self, enabled):
        """设置按钮启用状态"""
        self.prev_btn.setEnabled(enabled)
        self.next_btn.setEnabled(enabled)
        self.random_btn.setEnabled(enabled)
        self.auto_switch_btn.setEnabled(enabled)
        self.download_btn.setEnabled(enabled)
        self.download_history_btn.setEnabled(enabled)
        self.refresh_btn.setEnabled(enabled)
        self.selected_date_btn.setEnabled(enabled and self.calendar.selectedDate() <= QDate.currentDate())
        
    def on_calendar_selection_changed(self):
        """日历选择变化时更新下载按钮状态"""
        selected_date = self.calendar.selectedDate()
        today = QDate.currentDate()
        
        if selected_date > today:
            self.selected_date_btn.setEnabled(False)
            self.selected_date_btn.setToolTip("无法下载未来日期的壁纸")
        else:
            self.selected_date_btn.setEnabled(not self.is_setting_wallpaper)
            self.selected_date_btn.setToolTip("")
            
    def load_wallpaper_info(self):
        """加载壁纸信息文件"""
        self.wallpaper_info = {}
        if os.path.exists(self.wallpaper_info_file):
            try:
                with open(self.wallpaper_info_file, 'r', encoding='utf-8') as f:
                    for line in f:
                        if ':' in line:
                            date_str, title = line.strip().split(':', 1)
                            self.wallpaper_info[date_str] = title
            except Exception as e:
                print(f"加载壁纸信息文件失败: {e}")
                
    def save_wallpaper_info(self, date_str, title):
        """保存壁纸信息到文件"""
        self.wallpaper_info[date_str] = title
        try:
            with open(self.wallpaper_info_file, 'w', encoding='utf-8') as f:
                for date, wall_title in self.wallpaper_info.items():
                    f.write(f"{date}:{wall_title}\n")
        except Exception as e:
            print(f"保存壁纸信息文件失败: {e}")
            
    def get_wallpaper_title(self, date_str):
        """获取壁纸标题"""
        return self.wallpaper_info.get(date_str, "未知标题")
        
    def load_wallpapers(self):
        """加载壁纸并更新日历显示"""
        self.wallpapers_list = self.get_all_wallpapers()
        self.update_calendar_dates()
        
        if self.wallpapers_list:
            self.current_index = 0
            self.update_current_wallpaper_label()
            self.status_label.setText(f"✅ 已加载 {len(self.wallpapers_list)} 张壁纸")
        else:
            self.current_wallpaper_label.setText("当前壁纸: 无")
            self.status_label.setText("❌ 没有找到壁纸")
            
    def update_calendar_dates(self):
        """更新日历中有壁纸的日期标记"""
        self.wallpaper_dates.clear()
        
        has_wallpaper_format = QTextCharFormat()
        has_wallpaper_format.setBackground(QBrush(QColor(46, 204, 113, 150)))
        has_wallpaper_format.setForeground(QBrush(QColor(255, 255, 255)))
        has_wallpaper_format.setFontWeight(QFont.Bold)
        
        today = QDate.currentDate()
        future_format = QTextCharFormat()
        future_format.setForeground(QBrush(QColor(100, 100, 100)))
        future_format.setBackground(QBrush(QColor(60, 60, 60)))
        
        for date in self.wallpaper_dates:
            self.calendar.setDateTextFormat(date, QTextCharFormat())
        
        for wallpaper in self.wallpapers_list:
            filename = os.path.basename(wallpaper)
            if filename.startswith('bing_') and len(filename) > 10:
                date_str = filename[5:15]
                try:
                    date = QDate.fromString(date_str, "yyyy-MM-dd")
                    if date.isValid():
                        self.wallpaper_dates.add(date)
                        self.calendar.setDateTextFormat(date, has_wallpaper_format)
                except:
                    continue
        
        future_date = today.addDays(1)
        while future_date <= self.calendar.maximumDate():
            self.calendar.setDateTextFormat(future_date, future_format)
            future_date = future_date.addDays(1)
                    
    def on_calendar_date_clicked(self, date):
        """日历日期点击事件"""
        today = QDate.currentDate()
        
        if date > today:
            QMessageBox.information(self, "提示", "无法选择未来日期")
            return
            
        date_str = date.toString("yyyy-MM-dd")
        wallpaper_path = os.path.join(self.wallpapers_dir, f"bing_{date_str}.jpg")
        
        if os.path.exists(wallpaper_path):
            self.set_wallpaper_async(wallpaper_path)
            
            if wallpaper_path in self.wallpapers_list:
                self.current_index = self.wallpapers_list.index(wallpaper_path)
        else:
            reply = QMessageBox.question(self, "下载壁纸", 
                                       f"{date_str} 的壁纸不存在，是否下载？",
                                       QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.download_specific_date(date)
                
    def download_specific_date(self, date):
        """下载特定日期的壁纸"""
        date_str = date.toString("yyyy-MM-dd")
        self.status_label.setText(f"⬇️ 正在下载 {date_str} 的壁纸...")
        self.show_tray_notification(f"正在下载 {date_str} 的壁纸")
        
        def download_thread():
            today = QDate.currentDate()
            days_diff = date.daysTo(today)
            
            wallpaper_url, title, downloaded_date = self.get_bing_wallpaper_url(idx=days_diff)
            
            if not wallpaper_url:
                self.status_label.setText(f"❌ 无法获取 {date_str} 的壁纸")
                self.show_tray_notification(f"无法获取 {date_str} 的壁纸")
                return
            
            wallpaper_path = os.path.join(self.wallpapers_dir, f"bing_{date_str}.jpg")
            
            if self.download_image(wallpaper_url, wallpaper_path):
                if title:
                    self.save_wallpaper_info(date_str, title)
                self.status_label.setText(f"✅ {date_str} 壁纸下载完成: {title}")
                self.show_tray_notification(f"{date_str} 壁纸下载完成: {title}")
                self.load_wallpapers()
                self.set_wallpaper_async(wallpaper_path)
            else:
                self.status_label.setText(f"❌ {date_str} 壁纸下载失败")
                self.show_tray_notification(f"{date_str} 壁纸下载失败")
        
        threading.Thread(target=download_thread, daemon=True).start()
        
    def download_selected_date(self):
        """下载选中日期的壁纸"""
        selected_date = self.calendar.selectedDate()
        today = QDate.currentDate()
        
        if selected_date > today:
            QMessageBox.warning(self, "错误", "无法下载未来日期的壁纸")
            return
            
        self.download_specific_date(selected_date)
        
    def jump_to_today(self):
        """跳转到今天"""
        today = QDate.currentDate()
        self.calendar.setSelectedDate(today)
        
    def update_current_wallpaper_label(self):
        """更新当前壁纸标签"""
        if self.wallpapers_list and 0 <= self.current_index < len(self.wallpapers_list):
            current_file = os.path.basename(self.wallpapers_list[self.current_index])
            date_str = current_file[5:15]
            title = self.get_wallpaper_title(date_str)
            self.current_wallpaper_label.setText(f"🎨 当前壁纸: {date_str}\n{title}")
            
    def previous_wallpaper(self):
        """切换到上一张壁纸"""
        if not self.wallpapers_list or self.is_setting_wallpaper:
            return
            
        self.current_index = (self.current_index - 1) % len(self.wallpapers_list)
        self.set_wallpaper_async(self.wallpapers_list[self.current_index])
        self.show_tray_notification("切换到上一张壁纸")
        
    def next_wallpaper(self):
        """切换到下一张壁纸"""
        if not self.wallpapers_list or self.is_setting_wallpaper:
            return
            
        self.current_index = (self.current_index + 1) % len(self.wallpapers_list)
        self.set_wallpaper_async(self.wallpapers_list[self.current_index])
        self.show_tray_notification("切换到下一张壁纸")
        
    def random_wallpaper(self):
        """随机切换到一张壁纸"""
        if not self.wallpapers_list or self.is_setting_wallpaper:
            return
            
        old_index = self.current_index
        while self.current_index == old_index and len(self.wallpapers_list) > 1:
            self.current_index = random.randint(0, len(self.wallpapers_list) - 1)
            
        self.set_wallpaper_async(self.wallpapers_list[self.current_index])
        self.show_tray_notification("随机切换壁纸")
        
    def start_auto_switch(self):
        """开始自动切换"""
        if not self.wallpapers_list:
            QMessageBox.warning(self, "警告", "没有可用的壁纸！")
            return
            
        total_seconds = self.get_total_seconds()
        if total_seconds < 10:
            QMessageBox.warning(self, "警告", "间隔时间不能小于10是!")
            return
            
        self.switch_timer.start(total_seconds * 1000)
        self.remaining_seconds = total_seconds
        self.countdown_timer.start(1000)
        
        self.is_auto_switch = True
        self.auto_switch_btn.setEnabled(False)
        self.stop_auto_btn.setEnabled(True)
        
        self.update_total_interval_label()
        self.status_label.setText("▶ 自动切换已启动")
        self.show_tray_notification("自动切换已启动")
        self.update_countdown_label()
        
    def stop_auto_switch(self):
        """停止自动切换"""
        self.switch_timer.stop()
        self.countdown_timer.stop()
        self.is_auto_switch = False
        self.auto_switch_btn.setEnabled(True)
        self.stop_auto_btn.setEnabled(False)
        self.status_label.setText("⏸ 自动切换已停止")
        self.show_tray_notification("自动切换已停止")
        self.update_countdown_label()
        
    def auto_switch_wallpaper(self):
        """自动切换壁纸"""
        if self.wallpapers_list and not self.is_setting_wallpaper:
            self.check_and_download_today_wallpaper()
            self.random_wallpaper()
            total_seconds = self.get_total_seconds()
            self.remaining_seconds = total_seconds

    def get_bing_wallpaper_url(self, region="en-US", resolution="1920x1080", idx=0):
        """获取Bing壁纸URL"""
        api_url = f"https://www.bing.com/HPImageArchive.aspx?format=js&idx={idx}&n=1&mkt={region}"
        
        try:
            response = requests.get(api_url)
            response.raise_for_status()
            data = response.json()
            
            if not data["images"]:
                return None, None, None
            
            image_url = data["images"][0]["url"]
            full_url = urljoin("https://www.bing.com", image_url)
            
            if resolution:
                full_url = full_url.replace("1920x1080", resolution)
            
            title = data["images"][0]["title"]
            
            if "enddate" in data["images"][0]:
                date_str = data["images"][0]["enddate"]
                date_obj = datetime.strptime(date_str, "%Y%m%d")
                date_formatted = date_obj.strftime("%Y-%m-%d")
            else:
                date_obj = datetime.now() - timedelta(days=idx)
                date_formatted = date_obj.strftime("%Y-%m-%d")
            
            return full_url, title, date_formatted
        except Exception as e:
            print(f"获取Bing壁纸失败: {e}")
            return None, None, None

    def download_image(self, url, save_path):
        """下载图片"""
        try:
            response = requests.get(url, stream=True)
            response.raise_for_status()
            
            with open(save_path, 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192):
                    file.write(chunk)
            
            return True
        except Exception as e:
            print(f"下载图片失败: {e}")
            return False

    def download_daily_wallpaper(self):
        """下载今日壁纸"""
        self.status_label.setText("⬇️ 正在下载今日壁纸...")
        self.show_tray_notification("正在下载今日壁纸")
        
        def download_thread():
            wallpaper_url, title, date_str = self.get_bing_wallpaper_url(idx=0)
            
            if not wallpaper_url:
                self.status_label.setText("❌ 无法获取今日壁纸URL")
                self.show_tray_notification("无法获取今日壁纸")
                return
            
            wallpaper_path = os.path.join(self.wallpapers_dir, f"bing_{date_str}.jpg")
            
            if self.download_image(wallpaper_url, wallpaper_path):
                if title:
                    self.save_wallpaper_info(date_str, title)
                self.status_label.setText(f"✅ 今日壁纸下载完成: {title}")
                self.show_tray_notification(f"今日壁纸下载完成: {title}")
                self.load_wallpapers()
                self.set_wallpaper_async(wallpaper_path)
            else:
                self.status_label.setText("❌ 今日壁纸下载失败")
                self.show_tray_notification("今日壁纸下载失败")
        
        threading.Thread(target=download_thread, daemon=True).start()

    def download_historical_wallpapers(self):
        """下载历史壁纸"""
        self.status_label.setText("⬇️ 开始下载历史壁纸...")
        self.show_tray_notification("开始下载历史7天壁纸")
        
        def download_thread():
            os.makedirs(self.wallpapers_dir, exist_ok=True)
            downloaded_count = 0
            
            for i in range(7):
                wallpaper_url, title, date_str = self.get_bing_wallpaper_url(idx=i)
                
                if not wallpaper_url:
                    continue
                
                wallpaper_path = os.path.join(self.wallpapers_dir, f"bing_{date_str}.jpg")
                
                if os.path.exists(wallpaper_path):
                    continue
                
                if self.download_image(wallpaper_url, wallpaper_path):
                    if title:
                        self.save_wallpaper_info(date_str, title)
                    downloaded_count += 1
                
                time.sleep(1)
            
            self.status_label.setText(f"✅ 历史壁纸下载完成，新增 {downloaded_count} 张")
            self.show_tray_notification(f"历史壁纸下载完成，新增 {downloaded_count} 张")
            self.load_wallpapers()
        
        threading.Thread(target=download_thread, daemon=True).start()

    def get_all_wallpapers(self):
        """获取所有壁纸文件"""
        if not os.path.exists(self.wallpapers_dir):
            return []
        
        wallpapers = []
        for file in os.listdir(self.wallpapers_dir):
            if file.lower().endswith('.jpg') and file.startswith('bing_'):
                wallpapers.append(os.path.join(self.wallpapers_dir, file))
        
        return sorted(wallpapers, reverse=True)

def main():
    # 创建应用实例
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)  # 重要：防止关闭窗口时退出应用
    
    # 设置应用程序显示名称
    app.setApplicationName("Bing壁纸管理器")
    app.setApplicationDisplayName("Bing壁纸管理器")
    
    # 创建主窗口
    window = BingWallpaperApp()
    
    # 检查系统是否支持托盘图标
    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(None, "系统托盘", "系统不支持托盘图标，程序将以普通模式运行")
    else:
        print("系统托盘功能已启用")
    
    # 显示窗口
    window.show()
    
    # 运行应用
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()